package com.shou.lifecollege.framework.Security.handle;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.shou.lifecollege.framework.Common.result.RequestResult;
import com.shou.lifecollege.framework.Common.util.ServletUtils;
import com.shou.lifecollege.framework.Security.core.TokenManager;
import com.shou.lifecollege.framework.Security.model.LoginUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: luotian
 * @Date: 2022/11/24 17:30
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    private final TokenManager tokenManager;

    public LogoutSuccessHandlerImpl(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser=tokenManager.getLoginUser(request);
        if(ObjectUtil.isNotNull(loginUser))
        {
            tokenManager.removeToken(loginUser.getToken());
        }
        ServletUtils.renderString(response, JSON.toJSONString(RequestResult.success("退出成功！")));

    }
}
